package com.iamteer.servlet;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.iamteer.entity.Category;

@WebServlet("/category")
public class CategoryServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

/*	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		List<Category> list = categoryService.getAll();
		config.getServletContext().setAttribute("category", list);
	}*/
	
	public Object add(HttpServletRequest request, HttpServletResponse response) {
		String name = request.getParameter("category");
		Category category = new Category();
		category.setcName(name);
		categoryService.add(category);
		return request.getRequestDispatcher("/category?method=list");
	}
	
	public Object delete(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		categoryService.delete(Integer.parseInt(id));
		return request.getRequestDispatcher("/category?method=list");
	}

	public Object update(HttpServletRequest request, HttpServletResponse response) throws IllegalAccessException, InvocationTargetException {
		Category category = new Category();
		String name = request.getParameter("category");
		String id = request.getParameter("id");
		category.setcName(name);
		category.setId(Integer.parseInt(id));
//		Map<String, String[]> map = request.getParameterMap();
//		BeanUtils.populate(category, map);
		categoryService.update(category);
		return request.getRequestDispatcher("/category?method=list");
	}
	
	public Object list(HttpServletRequest request, HttpServletResponse response) {
		List<Category> list = categoryService.query();
		request.setAttribute("categoryList", list);
		return request.getRequestDispatcher("/sys/category/categoryList.jsp");
	}
	
	public Object show(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		Category category = categoryService.findById(Integer.parseInt(id));
		request.setAttribute("category", category);
		return request.getRequestDispatcher("/sys/category/updateCategory.jsp");
	}
}
